import os, time
from time import sleep
from PySide6.QtWidgets import QMainWindow, QMessageBox
from PySide6.QtCore import Slot, QCoreApplication, QFile
from Devices.Device import Device, ChiotDevice
from Devices.DeviceWindow import DeviceWindow
from Forms.BleFunctionWindow import BleFunctionWindow
from Forms.ScanDeviceWindow import ScanDeviceWindow
from Components.MessageBoxFunc import MessageBoxFunc
from Funcs.Config import Config

from Devices.Chiot.Bulb.Forms.BulbWindow import BulbWindow
from Devices.Chiot.MatterBulb.Forms.MatterBulbWindow import MatterBulbWindow
from Devices.Chiot.MatterPlug.Forms.MatterPlugWindow import MatterPlugWindow

from Devices.Chiot.BsDevs.Dimmer.Forms.DimmerWindow import DimmerWindow
from Devices.Chiot.BsDevs.Door.Forms.DoorWindow import DoorWindow
from Devices.Chiot.BsDevs.FallSensor.Forms.FallSensorWindow import FallSensorWindow
from Devices.Chiot.BsDevs.Humiture.Forms.HumitureWindow import HumitureWindow
from Devices.Chiot.BsDevs.Motion.Forms.MotionWindow import MotionWindow
from Devices.Chiot.BsDevs.Plug.Forms.PlugWindow import PlugWindow
from Devices.Chiot.BsDevs.Sensor.Forms.SensorWindow import SensorWindow
from Devices.Chiot.BsDevs.Sos.Forms.SosWindow import SosWindow
from Devices.Chiot.BsDevs.Stripe.Forms.StripeWindow import StripeWindow
from Devices.Chiot.BsDevs.Switch.Forms.SwitchWindow import SwitchWindow
from Devices.Chiot.BsDevs.TestPlug.Forms.TestPlugWindow import TestPlugWindow
from Devices.Chiot.BsDevs.Water.Forms.WaterWindow import WaterWindow

from Devices.Andlink.Forms.AndlinkWindow import AndlinkWindow
from Devices.Andlink.AndlinkWaterleak.Forms.AndlinkWaterleakWindow import AndlinkWaterleakWindow

# 导入我们生成的界面
from Forms.MainWindow_UI import Ui_FormMainWindow
 
# 继承QWidget类，以获取其属性和方法
class FormMainWindow(QMainWindow):
    def __init__(self, parent = None):
        super().__init__(parent)
        self.__ui = Ui_FormMainWindow()
        self.__ui.setupUi(self)
        self.setWindowTitle(self.windowTitle() + " V" + QCoreApplication.applicationVersion())
        
        self.__ScanDevice = ScanDeviceWindow()
        self.__ScanDevice.ConnectDevice.connect(self.on_ConnectDevice)
        
        self.__BleFunction = BleFunctionWindow()

    def Init(self):
        self.on_actionScan_triggered()

    @Slot()
    def on_DeviceWindowClose(self):
        pass
        # time.sleep(0.1)
        # try:
        #     for subWindow in self.__ui.mdiArea.subWindowList():
        #         if subWindow is not None:
        #             subWindow.showMaximized()
        # except:
        #     pass

    @Slot()
    def on_actionScan_triggered(self):
        SupportDevicesPath = Config.GetCurrentPath() + "/SupportDevices.json"
        print(SupportDevicesPath)

        file = QFile(SupportDevicesPath)
        file.open(QFile.ReadOnly)
        if (file.isOpen()):
            bytes = file.readAll()
            file.close()
            if (not Device.InitSupportDeviceList(bytes.toStdString())):
                MessageBoxFunc.ShowMessageBox("初始化", "初始化支持设备列表失败!", self, QMessageBox.Critical)
        else:
            MessageBoxFunc.ShowMessageBox("初始化", "初始化支持设备列表失败，请检查目录下是否有\"SupportDevices.json\"!", self, QMessageBox.Critical)

        self.__ScanDevice.Init()
        self.__ScanDevice.showNormal()
        self.__ScanDevice.activateWindow()

    @Slot()
    def on_actionReconnect_triggered(self):
        if (None != self.__ui.mdiArea.currentSubWindow()):
            self.__ui.mdiArea.currentSubWindow().ReConnect()

    @Slot()
    def on_actionBleFunction_triggered(self):
        self.__BleFunction.showNormal()
        self.__BleFunction.activateWindow()

    def LoadWindowModule(self, supportDevice):
        window_model = globals()[supportDevice.deviceWindow]
        if (window_model is None):
            MessageBoxFunc.ShowMessageBox("加载模块", "加载模块\"" + supportDevice.deviceWindow + "\"失败!", self, QMessageBox.Critical)
            self.__ScanDevice.activateWindow()
            return None

        deviceWindow:DeviceWindow = window_model(supportDevice, self)

        return deviceWindow

    def on_ConnectDevice(self, device):
        windowList = self.__ui.mdiArea.subWindowList()
        for deviceWindow in windowList:
            if device.GetIP() == deviceWindow.GetDeviceIP():
                deviceWindow.showMaximized()
                deviceWindow.activateWindow()
                return

        supportDevice = Device.GetSupportChiotDeviceByDisplayName(device.GetDisplayName())
        if supportDevice is None:
            supportDevice = Device.GetSupportAndlinkDeviceByDisplayName(device.GetDisplayName())

        if supportDevice is None:
            MessageBoxFunc.ShowMessageBox("连接设备", "不支持的设备类型!", self, QMessageBox.Critical)
            self.__ScanDevice.activateWindow()
            return

        deviceWindow = self.LoadWindowModule(supportDevice)
        if not deviceWindow is None:
            if (deviceWindow.Init(device.GetIP())):
                deviceWindow.destroyed.connect(self.on_DeviceWindowClose)

                self.__ui.mdiArea.addSubWindow(deviceWindow)
                if isinstance(device, ChiotDevice):
                    if supportDevice.deviceEncrypt:
                        deviceWindow.VerifyConnect(device.getCmdPort(), device.getLogPort())
                    else:
                        deviceWindow.Connect(device.getCmdPort(), device.getLogPort())
                else:
                    deviceWindow.Connect(0, 0)

                deviceWindow.showMaximized()
                deviceWindow.activateWindow()
            else:
                MessageBoxFunc.ShowMessageBox("连接设备", "初始化失败，请检查连接参数!", self, QMessageBox.Critical)
                self.__ScanDevice.activateWindow()

    def closeEvent(self, event):
        self.__ScanDevice.close()
        for deviceWindow in self.__ui.mdiArea.subWindowList():
            deviceWindow.close()

        os._exit(0)
